const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");
const uuid = require("uuid")
//服务器功能没有问题
http
  .createServer((req, res) => {
    if (req.url !== "/favicon.ico") {
      const urlObj = url.parse(req.url, true);
      switch (urlObj.pathname) {
        case "/api":
          getajax(req, res, urlObj);
          break;
        default:
          getfile(req, res, urlObj);
      }
    }
  })
  .listen("81", function () {
    console.log("111");
  });

//渲染功能没有问题
function getfile(req, res, urlObj) {
  fs.readFile("../www" + urlObj.pathname, (err, data) => {
    if (err) {
      res.write("404");
    } else {
      res.write(data);
    }
    res.end();
  });
}

function getajax(req, res, urlObj) {
  var data = "";
  req.on("data", (s) => {
    data += s;
  });
  req.on("end", () => {
    if (data === "") {
      data = urlObj.query;
    } else {
      data = querystring.parse(data);
    }
    switch (data.type) {
      case "login":
        login(req, res, data);
        break;
      case "register":
        register(req, res, data);
        break;
      case "goods":
        goods(req, res, data)
        break;
      case "goodsRender":
        goodsRender(req, res, data)
        break;
    }
    res.end();
  });
}

var arr = [];

function login(req, res, data) {

  let i;
  let onoff = arr.some((val, idx) => {
    i = idx;
    return val.user === data.user;
  });
  let Msg = {};
  if (onoff) {
    if (arr[i].pass === data.pass) {
      Msg = {
        code: 400,
        msg: "登录成功",
        data: {
          user: arr[i].user,
          pass: arr[i].pass,
          userId: arr[i].userId,
          type: arr[i].type
        }
      };
      res.write(JSON.stringify(Msg));
    } else {
      Msg = {
        code: 2,
        msg: "密码错误",
      };
      res.write(JSON.stringify(Msg));
    }
  } else {
    Msg = {
      code: 0,
      msg: "用户名不存在",
    };
    res.write(JSON.stringify(Msg));
  }
}

function register(req, res, data) {
  let i;
  let onoff = arr.some((val, idx) => {
    i = idx;
    return val.user === data.user;
  });
  let Msg = {};
  if (onoff) {
    Msg = {
      code: 1,
      msg: "用户名重复",
    };
    res.write(JSON.stringify(Msg));
  } else {
    var id = uuid.v1()
    arr.push({
      user: data.user,
      pass: data.pass,
      userId: id,
      type: data.type
    });
    Msg = {
      code: 200,
      msg: "注册成功",
      data: {
        user: data.user,
        pass: data.pass,
        userId: id,
        type: data.type
      }
    };
    res.write(JSON.stringify(Msg));
  }
}

function goods(req, res, data) {
  res.write(JSON.stringify(data));
}

function goodsRender(req, res, data) {
  // console.log(data)

  // arr.map((val, idx, self) => {
  //   if (val)
  // })
}